// pages/profile/profile.js
import { checkPageLogin, checkMethodLogin } from '../../utils/login-check.js'
import authManager from '../../utils/auth.js'
import { userAPI } from '../../utils/api.js'
import cosUploader from '../../utils/cos-upload.js'

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
      phone: '',
      memberLevel: '',
      points: 0
    },
    hasUserInfo: false,
    showLoginModal: false,
    showAboutModal: false,
    isUpdating: false, // 是否正在更新用户信息
    menuItems: [
      {
        id: 'address',
        emoji: '📍',
        title: '收货地址',
        subtitle: '管理我的地址',
        url: '/pages/address/address'
      },
      {
        id: 'coupon',
        emoji: '🎫',
        title: '优惠券',
        subtitle: '3张可用',
        url: '/pages/coupon/coupon'
      },
      {
        id: 'favorite',
        emoji: '❤️',
        title: '我的收藏',
        subtitle: '收藏的商品',
        url: '/pages/favorite/favorite'
      },
      {
        id: 'history',
        emoji: '👁️',
        title: '浏览历史',
        subtitle: '最近看过的商品',
        url: '/pages/history/history'
      }
    ],
    settingItems: [
      // {
      //   id: 'feedback',
      //   emoji: '💬',
      //   title: '意见反馈',
      //   url: '/pages/feedback/feedback'
      // },
      {
        id: 'about',
        emoji: 'ℹ️',
        title: '关于我们',
        url: '/pages/about/about'
      },
      // {
      //   id: 'privacy',
      //   emoji: '🔒',
      //   title: '隐私政策',
      //   url: '/pages/privacy/privacy'
      // }
    ],
    statistics: {
      totalOrders: 24,
      totalSpent: 2680,
      favoriteCount: 12,
      couponCount: 3
    }
  },

  onLoad: function (options) {
    this.loadUserInfo()
  },

  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }
    
    // 每次显示页面时检查登录状态
    this.checkLoginStatus()
  },

  // 选择头像
  onChooseAvatar: function(e) {
    const { avatarUrl } = e.detail
    this.setData({
      isUpdating: true
    })
    
    // 使用COS上传头像
    cosUploader.uploadAvatar(avatarUrl).then(uploadResult => {
      console.log('COS上传成功:', uploadResult)
      
      // 使用上传后的文件URL更新用户信息
      const updateData = {
        nickname: this.data.userInfo.nickName || '',
        avatar: uploadResult.url
      }
      
      return userAPI.setUserProfile(updateData)
    }).then(response => {
      console.log('更新头像成功:', response)
      
      // 更新本地显示
      this.setData({
        'userInfo.avatarUrl': avatarUrl
      })
      
      wx.showToast({
        title: '头像更新成功',
        icon: 'success'
      })
    }).catch(error => {
      console.error('更新头像失败:', error)
      wx.showToast({
        title: '头像更新失败',
        icon: 'none'
      })
    }).finally(() => {
      this.setData({
        isUpdating: false
      })
    })
  },

  // 编辑昵称
  onEditNickname: function() {
    wx.showModal({
      title: '修改昵称',
      editable: true,
      placeholderText: '请输入昵称',
      success: (res) => {
        if (res.confirm && res.content) {
          this.setData({
            'userInfo.nickName': res.content,
            isUpdating: true
          })
          
          // 立即更新昵称到服务器
          const updateData = {
            nickname: res.content,
            avatar: this.data.userInfo.avatarUrl || ''
          }
          
          userAPI.setUserProfile(updateData).then(response => {
            console.log('更新昵称成功:', response)
            wx.showToast({
              title: '昵称更新成功',
              icon: 'success'
            })
          }).catch(error => {
            console.error('更新昵称失败:', error)
            wx.showToast({
              title: '昵称更新失败',
              icon: 'none'
            })
          }).finally(() => {
            this.setData({
              isUpdating: false
            })
          })
        }
      }
    })
  },

  // 编辑手机号
  onEditPhone: function() {
    wx.navigateTo({
      url: '/pages/edit-phone/edit-phone'
    })
  },

  // 查看会员详情
  onMemberDetail: function() {
    wx.navigateTo({
      url: '/pages/member/member'
    })
  },

  // 余额详情
  onBalanceDetail: function() {
    wx.navigateTo({
      url: '/pages/balance-record/index'
    })
  },

  // 积分详情
  onCreditDetail: function() {
    wx.navigateTo({
      url: '/pages/credit-record/index'
    })
  },

  // 菜单项点击
  onMenuTap: function(e) {
    if (!this.data.hasUserInfo) {
      this.showLoginModal()
      return
    }
    
    const itemId = e.currentTarget.dataset.id
    const item = this.data.menuItems.find(item => item.id === itemId)
    
    if (item && item.url) {
      wx.navigateTo({
        url: item.url
      })
    }
  },

  // 设置项点击
  onSettingTap: function(e) {
    const itemId = e.currentTarget.dataset.id
    const item = this.data.settingItems.find(item => item.id === itemId)
    
    if (itemId === 'about') {
      // 显示关于我们弹窗
      this.showAboutModal()
    } else if (item && item.url) {
      wx.navigateTo({
        url: item.url
      })
    }
  },

  // 统计项点击
  onStatTap: function(e) {
    if (!this.data.hasUserInfo) {
      this.showLoginModal()
      return
    }
    
    const type = e.currentTarget.dataset.type
    
    switch (type) {
      case 'orders':
        wx.switchTab({
          url: '/pages/order/order'
        })
        break
      case 'favorite':
        wx.navigateTo({
          url: '/pages/favorite/favorite'
        })
        break
      case 'coupon':
        wx.navigateTo({
          url: '/pages/coupon/coupon'
        })
        break
    }
  },

  // 客服
  onContact: function() {
    wx.showModal({
      title: '客服联系方式',
      content: '客服电话：400-888-8888\n工作时间：9:00-21:00',
      showCancel: false
    })
  },

  // 设置
  onSettings: function() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    })
  },

  // 退出登录
  onLogout: function() {
    if (!this.data.hasUserInfo) {
      this.showLoginModal()
      return
    }
    
    wx.showModal({
      title: '确认退出登录？',
      success: (res) => {
        if (res.confirm) {
          this.logout()
        }
      }
    })
  },

  // 检查登录状态
  checkLoginStatus: function() {
    const token = wx.getStorageSync('token')
    
    if (token) {
      // 有token，获取用户信息
      this.loadUserInfoFromAPI()
    } else {
      this.setData({
        hasUserInfo: false,
        userInfo: {
          avatarUrl: defaultAvatarUrl,
          nickName: '',
          phone: '',
          memberLevel: '',
          points: 0
        }
      })
    }
  },

  // 从API获取用户信息
  loadUserInfoFromAPI: function() {
    userAPI.getUserProfile().then(response => {
      console.log('获取用户信息成功:', response)
      const userInfo = response.info || response
      this.setData({
        userInfo: {
          avatarUrl: userInfo.avatar || defaultAvatarUrl,
          nickName: userInfo.nickname || userInfo.nickname || '',
          phone: userInfo.mobile || userInfo.phone || '',
          memberLevel: userInfo.memberLevel || '',
          points: userInfo.credit || userInfo.points || 0,
          balance: userInfo.balance || 0
        },
        hasUserInfo: true
      })
    }).catch(error => {
      console.error('获取用户信息失败:', error)
      // 获取用户信息失败，可能是token过期
      this.setData({
        hasUserInfo: false,
        userInfo: {
          avatarUrl: defaultAvatarUrl,
          nickName: '',
          phone: '',
          memberLevel: '',
          points: 0,
          balance: 0
        }
      })
    })
  },

  // 加载用户信息
  loadUserInfo: function() {
    this.checkLoginStatus()
  },

  // 更新用户信息
  updateUserInfo: function() {
    // 构建API请求数据
    const updateData = {
      nickname: this.data.userInfo.nickName || '',
      avatar: this.data.userInfo.avatarUrl || ''
    }
    
    // 调用API更新用户信息
    userAPI.setUserProfile(updateData).then(response => {
      console.log('更新用户信息成功:', response)
      
      // 保存到缓存
      wx.setStorageSync('userInfo', this.data.userInfo)
      
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      })
    }).catch(error => {
      console.error('更新用户信息失败:', error)
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    })
  },

  // 刷新用户数据
  refreshUserData: function() {
    // 重新获取用户统计数据
    // 这里模拟数据更新
  },

  // 退出登录
  logout: function() {
    // 使用authManager退出登录
    authManager.logout()
    
    this.setData({
      userInfo: {
        avatarUrl: defaultAvatarUrl,
        nickName: '',
        phone: '',
        memberLevel: '',
        points: 0
      },
      hasUserInfo: false
    })
    
    wx.showToast({
      title: '已退出登录',
      icon: 'success'
    })
    
    // 跳转到登录页面
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },

  // 显示登录弹窗
  showLoginModal() {
    this.setData({ showLoginModal: true })
  },

  // 关闭登录弹窗
  onCloseLoginModal() {
    this.setData({ showLoginModal: false })
  },

  // 登录成功回调
  onLoginSuccess(e) {
    // 登录成功后重新获取用户信息
    this.setData({ showLoginModal: false })
    this.checkLoginStatus()
    
    wx.showToast({
      title: '登录成功',
      icon: 'success'
    })
  },

  // 显示关于我们弹窗
  showAboutModal() {
    this.setData({ showAboutModal: true })
  },

  // 关闭关于我们弹窗
  onCloseAboutModal() {
    this.setData({ showAboutModal: false })
  },

  // 打开地图
  onOpenMap() {
    const address = '广州市越秀区北京街道盐运西正街25号一楼'
    const latitude = 23.1218318939209  // 广州越秀区的大概坐标
    const longitude = 113.26551055908203
    
    wx.showActionSheet({
      itemList: ['打开微信地图', '复制地址'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 打开微信地图
          wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: 'OKEYDO TAP ROOM',
            address: address,
            scale: 18
          })
        } else if (res.tapIndex === 1) {
          // 复制地址
          wx.setClipboardData({
            data: address,
            success: () => {
              wx.showToast({
                title: '地址已复制',
                icon: 'success'
              })
            }
          })
        }
      }
    })
  },

  // 分享
  onShareAppMessage: function() {
    return {
      title: 'OKEYDO',
      path: '/pages/home/home',
      imageUrl: '/assets/images/share.jpg'
    }
  }
}) 